package com.inossem.allotin.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

import com.inossem.allotin.service.BluetoothLeService;
import com.orhanobut.logger.Logger;

/**
 * @author 王斯宇
 * @time on 2019/7/10 10:22
 * @email siyu.wang@inossem.com
 */
public class GattUpdateReceiver extends BroadcastReceiver {

    private ScanListener listener;

    public GattUpdateReceiver(ScanListener listener) {
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        //连接蓝牙设备成功
        if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
            Toast.makeText(context, "已连接", Toast.LENGTH_SHORT).show();
            log("蓝牙设备已连接");
        }
        //蓝牙设备断开
        else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
                .equals(action)) {
            log("已断开连接");
            Toast.makeText(context, "已断开连接", Toast.LENGTH_SHORT).show();
        }
        //获取到当前蓝牙设备支持的所有支持的服务和特性
        else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
                .equals(action)) {
            // Show all the supported services and characteristics on the
            // user interface.
            log("获取到支持的服务");
            listener.onGattServicesListener();

        }
        //获取到扫描内容
        else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
            log("获取到扫描内容:" + intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            String result = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
            if (listener != null) {
                listener.onResult(result);
            }
        }
    }

    private void log(String message) {
        Logger.i("-------------------------------" + message + "--------------------------------------");
    }

    public interface ScanListener {
        void onResult(String scanResult);

        void onGattServicesListener();
    }
}
